package myapps.myservlet;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import java.math.BigInteger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SignServlet
 */
public class SignServlet extends HttpServlet 
{
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignServlet() 
    {
        super();
    }
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException 
	{
		    	
    	res.setContentType("text/html; charset=UTF-8"); 
    	
    	PrintWriter out = res.getWriter();
    	
    	
    		
    		String username = req.getParameter("username");
    		String password = req.getParameter("password");
    		
    		if( username !=null  && password !=null)
    		{ 
    			boolean isLogined = false;
    			    			
    			//hash submitted password
    			MessageDigest md5Instace=null;
    			
 				try 
 				{
 					md5Instace = MessageDigest.getInstance("MD5");
 				} 
 				catch (NoSuchAlgorithmException e) 
 				{
 					e.printStackTrace();
 				}
 				
 		    	 md5Instace.update(password.getBytes(),0,password.length());
 		    	 
 		    	 String hashText = new BigInteger(1,md5Instace.digest()).toString(16);
 		    	 
    			 System.out.println(hashText);
    			
 		    	try 
 		    	{
					Class.forName("com.mysql.jdbc.Driver");
					Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/chat_group_db", "root", "");
					
					System.out.println(" da ket noi dc database de signin");
					Statement statement = connection.createStatement();
					ResultSet resultSet = statement.executeQuery("SELECT * FROM user_table WHERE username ='"+username+"' " +
					        		"AND password='"+hashText+"'");
					
					resultSet.last();
					
					if (resultSet.getRow() != 0)
					{
						isLogined=true;
					}
					
					if(isLogined)
				    {
							resultSet = statement.executeQuery("SELECT Username FROM user_online WHERE Username ='"+username+"'");
							resultSet.last();
							
							if (resultSet.getRow()!= 0)
							{
								out.println("<br/> Tài khoản <strong>"+username+"</strong> đã được đăng nhập rồi ");
								
								return;
							}
							
				    	  //Obtain the session object, create a new session if doesn't exist
				    	   HttpSession session = req.getSession(true);
				    	   
				           session.setAttribute("user_login", username);
				           
				           // set session variable : reading_index = 0 when user signed in
				           session.setAttribute("reading_index", 0);
				           
				           //write a record , this is a user online 
				           statement.executeUpdate("INSERT INTO user_online VALUES('"+username+"')");
				           
					       res.sendRedirect("index.html");		       
					       return;		    
				       }
				       else
				       {
				    	   //render page 
				    	    ServletContext context = getServletContext(); 
					   	    String path =context.getRealPath("/template/login.txt");
					   	    FileInputStream in = new FileInputStream(path);
					   	    InputStreamReader inr = new InputStreamReader(in, "UTF-8");
					   		BufferedReader br = new BufferedReader(inr);
					   		String line;
					   		
					   	    while((line = br.readLine())!= null)
					   	    {
					   	    	if(line.contains("submit"))
					   	    	{
					   	    	  //print notice after Login button
					   	    	  out.println("<div class ='notice'>Tên đăng nhập hoặc mật khẩu ko phù hợp</div>");
					   	    	}
					   	    	out.println(line);
					   	    }				    	  
				    	 }	//end login fails					
				} 
 		    	catch (Exception e) //catch connect sql
 		    	{
					
					e.printStackTrace();
				}
    		}// end if
    	
	}//end post
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		res.setContentType("text/html; charset=UTF-8");
		req.setCharacterEncoding("UTF-8");
		PrintWriter out = res.getWriter();

		ServletContext context = getServletContext(); 
	    String path =context.getRealPath("/template/login.txt");
	    FileInputStream in = new FileInputStream(path);
	    InputStreamReader inr = new InputStreamReader(in, "UTF-8");
		BufferedReader br = new BufferedReader(inr);
		String line;
		
	    while((line = br.readLine())!= null)
	    {
	    	out.println(line);
	    }

	}
}
